package protocol.channels.control;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

import protocol.Frame;
import protocol.control.Packet;
import virtualdatagramsocket.VirtualDatagramSocket;

public class ControlChannel {

	protected VirtualDatagramSocket socket;

	protected VirtualDatagramSocket getSocket() {
		return this.socket;
	}

	protected void setSocket(VirtualDatagramSocket socket) {
		this.socket = socket;
	}
	
	protected InetAddress sourceAddress;
	protected int sourcePort;
	
	/**
	 * 
	 * @param timeout
	 * @return
	 * @throws IOException
	 */
	protected Packet receive(int timeout) throws IOException {
		/**
		 * The biggest control channel 
		 * packet is 322 bytes
		 */
		byte[] data = new byte[322];
		DatagramPacket packet = new DatagramPacket(data, data.length);
		/**
		 * SocketTimeoutException will be thrown
		 * after time set with setSoTimeout() is elapsed.
		 */
		this.getSocket().setSoTimeout(1000 * timeout);
		try {
			this.getSocket().receive(packet);
			this.sourceAddress = packet.getAddress();
			this.sourcePort = packet.getPort();
			return new Packet(packet.getData());
		} catch (SocketTimeoutException e) {
			//System.out.println("Timeout");
			return null;
		}
	}
	
	/**
	 * 
	 * @param p
	 * @throws IOException
	 */
	protected void send(Frame p) throws IOException {
		byte[] data = p.build();
		DatagramPacket packet = new DatagramPacket(
				data, data.length);
		this.getSocket().send(packet);
	}

	/**
	 * 
	 * @param p
	 * @param address
	 * @param port
	 * @throws IOException
	 */
	protected void send(Frame p, InetAddress address, int port) throws IOException {
		byte[] data = p.build();
		DatagramPacket packet = new DatagramPacket(
				data, data.length, address, port);
		this.getSocket().send(packet);
	}

}